package com.woniuxy.personal.core.mq;

import com.rabbitmq.client.Channel;
import com.woniuxy.personal.core.constant.OrderConstant;
import com.woniuxy.personal.core.mapper.PlOrderMapper;
import com.woniuxy.personal.core.model.PlOrder;
import com.woniuxy.personal.core.vo.OrderVo;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Auther: binhu  <br/>
 * Date: 2021/6/30:16:09  <br/>
 * Description:
 */
@Component
public class DlqOrderConsumer {

    @Autowired
    private PlOrderMapper orderMapper;

    @RabbitHandler
    @RabbitListener(queues = "dlq-queue")
    public void processTtlOrder(@Payload OrderVo orderVo, Channel channel, @Headers Map headers) throws IOException {
        String ordernumber = (String) headers.get("spring_returned_message_correlation");

        PlOrder order = orderMapper.selectByOrdernumber(ordernumber);
        if(order.getStatus().equals(OrderConstant.PENDING_PAYMENT)){
            order.setStatus(OrderConstant.EXPIRED);
            orderMapper.updateById(order);
        }
        Long id = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(id,false);
        } catch (IOException e) {
            e.printStackTrace();
            channel.basicNack(id,false,false);
        }
    }
}
